﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DH.Web.Controllers;
using DH.Entity;
using DH.Service.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using DH.Service.Domain;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using DH.Web.Filter;
using DH.Core;
using DH.Web.MVC.Extensions;
using System.ComponentModel;
using DH.Web.Attributes;
using System.Reflection;
using DH.Core.Helper;
using Newtonsoft.Json;

namespace DH.Web.MVC.Controllers
{
    [Authorize]
    [Route("Category")]
    [Resource("Category(资源)")]
    [Description("Category(资源)")]
    [Guid("b8d64467-f898-4718-932e-73bb1d52adf5")]
    public class CategoryController : SiteController<CategoryEntity, CategoryViewModel, string>
    {

        CategoryService _categoryService;
        static Logger Logger = LogManager.GetCurrentClassLogger();
        public CategoryController(IServiceCollection serviceCollection,
                              CategoryService categoryService) : base(serviceCollection, categoryService)
        {
            _categoryService = categoryService;
          
        }

        [HttpGet]
        [Route("Index")]
        [UIView("Category首页")]
        [Description("Category首页")]
        [Guid("19235d38-a7e1-460f-867b-907deddbab58")]
        [UserPermissionFilter]
        public IActionResult Index()
        {
            //var userSessionEx = new UserSessionEx(_service);
            //userSessionEx.DepartmentId = CurrentUser.DepartmentId;
            //userSessionEx.IsAdmin = CurrentUser.IsAdmin;
            //userSessionEx.IsDeveloper = CurrentUser.IsDeveloper;
            //userSessionEx.LoginIP = CurrentUser.LoginIP;
            //userSessionEx.LoginTime = CurrentUser.LoginTime;
            //userSessionEx.RealName = CurrentUser.RealName;
            //userSessionEx.RoleId = CurrentUser.RoleId;

            ViewBag.CurrentUser = CurrentUserEx;
            ViewBag.CurrentViewId = "19235d38-a7e1-460f-867b-907deddbab58";

            return View();
        }

        [HttpGet]
        [Route("Categories")]
        [Function("获取Category列表")]
        [Description("获取Category列表")]
        [Guid("ddfbecd6-82f1-42e1-87ee-17d28dba8e82")]
        [UserPermissionFilter]
        public async Task<IActionResult> GetCategoryList()
       {
            PagedData<CategoryViewModel> models;
            var pagination = GetPagination();
            var queryKey = "";
            var queryKeys = Request.Query["queryKey"];
            if (queryKeys.Any())
            {
                queryKey = queryKeys[0];
            }

            var filterObj = new CategoryQueryDto();
            var filter = Request.Query["filter"];
            if (filter.Any())
            {
                if (filter[0]!="")
                {
                    filterObj = JsonConvert.DeserializeObject<CategoryQueryDto>(filter[0]);
                }
                
            }

            var res = await _categoryService.GetListAsync(queryKey, filterObj, pagination);
            models = res.ToViewModelPageData<CategoryEntity, CategoryViewModel>();

            foreach (var md in models.DataList)
            {
                md.ParentName = _categoryService.GetParentName(md.ParentCode);
                var simpleCodes= md.Code.Split(".");
                var simpleCode = simpleCodes[simpleCodes.Length-1];
                md.Code = simpleCode;
            }

            var result = new { total = models.TotalCount, rows = models.DataList };
            return Json(result);
        }


        [HttpGet]
        [Route("InitResource")]
        [Function("初始化资源",isManage:true)]
        [Description("初始化资源")]
        [Guid("11c5192b-4edd-4ec2-bbea-180f9a8f5971")]
        public IActionResult InitCategories()
        {
            //不是开发人员，无权执行
            if (!CurrentUser.IsDeveloper)
            {
                return InternalServerError(null,"非开发人员，无权执行此操作");
            }
            try
            {
                //生成资源
                var res = ImportCategories();
                if (res)
                {
                    return SuccessMessage("系统资源初始化成功");
                }
                else
                {
                    return Error("系统资源初始化失败");
                }

                
            }
            catch (Exception ex)
            {
                Logger.Error("初始化资源发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while initing Resource");
            }

            
        }

        private bool ImportCategories()
        {
            var assemblyStrings = new List<string> {
                            "DH.Web.MVC"
                        };
            var dlls = assemblyStrings.Select(Assembly.Load).ToList();

            var oldResources = _categoryService.GetAllResources(ConstHelper.CategoryResourceType);

            var categories = new List<CategoryViewModel>();

            foreach (var dll in dlls) {
                var types = dll.GetTypes();
                var controllerType = typeof(Web.Controllers.ControllerBase);

                foreach (var t in types)
                {
                    var isController = controllerType.IsAssignableFrom(t);//继承ControllerBase 的控制器
                    if (!isController)
                    {
                        continue ;
                    }
                    //获取资源名称
                    var controllerName = t.Name.Substring(0, t.Name.Length - "Controller".Length);
                    var resourceName = controllerName;//没有资源名称，默认取控制器名称
                    var resourceAttributes = t.GetCustomAttributes(typeof(ResourceAttribute),inherit:false);
                    if (resourceAttributes.Length>0)
                    {
                        var description = ((ResourceAttribute)resourceAttributes[0]).Description;
                        if (!string.IsNullOrWhiteSpace(description))
                        {
                            resourceName = description;
                        }

                    }
                    else
                    {
                        continue;
                    }
                    var guidAttribute = t.GetCustomAttribute(typeof(GuidAttribute));
                    var guid = ((GuidAttribute)guidAttribute).Description;
                    if (string.IsNullOrWhiteSpace(guid))
                    {
                        continue;
                    }
                    

                    var existResources = oldResources.Where(c => c.Id == guid);
                    if (!existResources.Any())
                    {
                        //生成实体
                        var categoryViewModle = new CategoryViewModel();
                        categoryViewModle.Id = guid;
                        categoryViewModle.Name = resourceName;
                        categoryViewModle.Code = ConstHelper.SystemRootCode + "." + controllerName;
                        categoryViewModle.CategoryCode = ConstHelper.CategoryResourceType;
                        categoryViewModle.ParentCode = ConstHelper.SystemRootCode;
                        categoryViewModle.Status = true;
                        categoryViewModle.Description = "";
                        categoryViewModle.UpdatedBy = CurrentUser.UserId;
                        categoryViewModle.CreatedBy = CurrentUser.UserId;

                        categories.Add(categoryViewModle);
                    }
                    
                    

                }
            }
            //批量保存
            _categoryService.InsertCategories(categories);

            return true;

        }


        [HttpPost]
        [Route("Add")]
        [Function("添加资源/字典", isManage: true)]
        [Guid("21013ebe-05f7-43dc-88aa-887b0e961b57")]
        public async Task<IActionResult> Add(CategoryViewModel input)
        {
            if (!ModelState.IsValid)
            {
                return ErrorMessage("实体类验证失败");
            }
            try
            {
                if (!string.IsNullOrWhiteSpace(input.Id))
                {
                    input.ParentCode = input.ParentCode ?? "DH";
                    input.Code = input.ParentCode + "." + input.Code;

                    var existDicCode = _categoryService.CheckHasRepeatCode(input.Code, input.Id);
                    if (existDicCode)
                    {
                        return Error("Code已存在");
                    }
                    input.UpdatedBy = CurrentUser.UserId;
                    await _categoryService.EditAsync(input);
                }
                else
                {
                    input.ParentCode = input.ParentCode?? "DH";
                    input.Code = input.ParentCode + "." + input.Code;
                    input.UpdatedBy = CurrentUser.UserId;
                    input.CreatedBy = CurrentUser.UserId;

                    //检查是否有重复code
                    var existDicCode = _categoryService.CheckHasRepeatCode(input.Code,"");
                    if (existDicCode)
                    {
                        return Error("Code已存在");
                    }

                    await _categoryService.AddAsync(input);
                }

                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("新增Category时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", nameof(RoleViewModel));
            }
        }

        [HttpPost]
        [Route("Delete")]
        [Function("删除资源/字典", isManage: true)]
        [Guid("1ad003a2-3ec9-4cff-a3fc-07544cf8ce3d")]
        public async  Task<IActionResult> Delete(string[] ids)
        {
            try
            {
                await _categoryService.DeleteAsync(ids);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("删除categories时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", ids);
            }
        }


        [HttpGet]
        [Route("GetDics")]
        [Function("获取字典")]
        [Guid("8b659837-feca-451e-bfae-71bf7bf5b583")]
        public IActionResult GetDics()
        {
            var dics= _categoryService.GetResources(ConstHelper.CategoryDicType);
            return new JsonResult(dics);
        }


        [HttpPost]
        [Route("EnableResource")]
        [Function("启用资源",isManage:true)]
        [Guid("ed70c27b-0f4b-4f10-8a2c-723b3a5d1de8")]
        public IActionResult EnableResource(string id)
        {
            try
            {
                _categoryService.EnabledResource(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("启用资源时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while enabling Role with id: {0}", id);
            }
        }

        [HttpPost]
        [Route("DisableResource")]
        [Function("禁用资源",isManage:true)]
        [Guid("56a606c0-1c46-4519-b200-92f2ffac54cf")]
        public IActionResult DisAbleResource(string id)
        {
            try
            {
                _categoryService.DisabledResource(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("禁用资源时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", id);
            }
        }

        
        [HttpGet]
        [Route("GetDicTree")]
        [Function("获取字典树")]
        [Guid("034c3d18-76f3-4b4b-b0b9-630fed1a14fa")]
        public IActionResult GetDicTree()
        {
            var res = _categoryService.GetDicSelects();
            return new JsonResult(res);
        }

        [HttpGet]
        [Route("GetDicDefaultTree")]
        [Function("获取字典默认树")]
        [Guid("0b69ad14-cd95-4620-abf4-183cb235a32e")]
        public IActionResult GetDicDefaultTree()
        {
            var defaultViewModel = new DicSelectViewModel();
            defaultViewModel.parentId = "";
            defaultViewModel.id = "DH";
            defaultViewModel.text = "根编码";

            var dics = new List<DicSelectViewModel>();
            dics.Add(defaultViewModel);

            return new JsonResult(dics);
        }


        [HttpGet]
        [Route("GetResourceTypeSelect")]
        [Function("获取资源类型下拉数据")]
        [Guid("7a124528-fdd2-4ee6-8112-46cc89aeeb53")]
        public IActionResult GetResourceTypeSelect()
        {
            var resources = _categoryService.GetResources(ConstHelper.CategoryResourceType);
            var resSelect = resources.ToDictionary(k=>k.Id,v=>v.Name);
            var res= new JsonResult(resSelect);
            return res;
        }

        [HttpGet]
        [Route("GetResources")]
        [Function("获取资源")]
        [Guid("0ea78aea-a599-4a4a-9ac8-53ebfb0da476")]
        public IActionResult GetResources()
        {
            var resources = _categoryService.GetResources(ConstHelper.CategoryResourceType);
            return new JsonResult(resources);
        }
        
    }
}